package org.zoomdev.zoom.web.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.common.Destroyable;
import org.zoomdev.zoom.ioc.Ioc;
import org.zoomdev.zoom.web.ExceptionHandler;
import org.zoomdev.zoom.web.action.ActionHandler;
import org.zoomdev.zoom.web.handlers.NotFoundFilterHandler;
import org.zoomdev.zoom.web.router.Router;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class MockWebService implements Destroyable {

    private final Router router;
    private final NotFoundFilterHandler notFoundHandler;

    private final ExceptionHandler exceptionHandler;

    private final Ioc ioc;

    private final FilterChain chain;

    public MockWebService(Ioc ioc) {
        this.ioc = ioc;
        this.router = ioc.fetch(Router.class);
        this.chain = MockUtils.filterChain();

        this.notFoundHandler = ioc.fetch(NotFoundFilterHandler.class);
        this.exceptionHandler = ioc.fetch(ExceptionHandler.class);

    }


    public Ioc getIoc() {
        return ioc;
    }

    public MockResponse execute(HttpServletRequest request) {
        MockResponse response = MockUtils.response();
        try {
            ActionHandler handler = router.match(request);
            if (handler == null) {
                notFoundHandler.handle(request, response, chain);
            }else{
                handler.handle(request, response);
            }
        } catch (Throwable e) {
            exceptionHandler.handle(request, response, e);
        }
        return response;
    }
    public void execute(HttpServletRequest request, HttpServletResponse response) {


        try {
            ActionHandler handler = router.match(request);
            if (handler == null) {
                notFoundHandler.handle(request, response, chain);
                return;
            }
            handler.handle(request, response);
        } catch (Throwable e) {
            exceptionHandler.handle(request, response, e);
        }
    }

    @Override
    public void destroy() {
        //  webService.destroy();
    }


}
